<?php

abstract class Model extends RecordObject
{
	public static function GetWritableRecordFactory()
	{
		$config = ConfigReaderFactory::getInstance()->getConfigReader(ImageInfrastructureServerConfig::CONFIG_FILE)->getConfig();
		$db = $config->db->writer;
		$user = $config->db->user;
		$pass = $config->db->pwd;
		$name = $config->db->name;
		return new WritableRecordFactory($db, $user, $pass, $name);
	}

	static public function GetReadableRecordFactory() {
		$config = ConfigReaderFactory::getInstance()->getConfigReader(ImageInfrastructureServerConfig::CONFIG_FILE)->getConfig();
		$readers = array();
		foreach ($config->db->readers->reader as $reader) {
			$readers[] = (string) $reader;
		}
		$i = array_rand($readers);

		$db = $readers[$i];
		$user = $config->db->user;
		$pass = $config->db->pwd;
		$name = $config->db->name;
		return new ReadableRecordFactory($db, $user, $pass, $name);
	}

	public function get($id)
	{
		if (!is_array($id)) {
			return self::GetReadableRecordFactory()->findInstance(get_class($this), $id);
		} else{
			return FALSE;
		}
	}

	public function insert()
	{
		try {
			return self::GetWritableRecordFactory()->insert($this);
		} catch (PDOException $e) {
			error_log('ERROR - PDOException:');
			error_log($e->getMessage());
			error_log($e->getTraceAsString());
			return FALSE;
		}
	}
	
	public function update()
	{
		try {
			return self::GetWritableRecordFactory()->save($this);
		} catch (PDOException $e) {
			error_log('ERROR - PDOException:');
			error_log($e->getMessage());
			error_log($e->getTraceAsString());
			return FALSE;
		}
	}
}

?>
